package com.aipartner.service.impl;

import com.aipartner.common.PageResult;
import com.aipartner.entity.ChatHistory;
import com.aipartner.mapper.ChatHistoryMapper;
import com.aipartner.service.ChatHistoryService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * Chat History Service Implementation
 * 
 * @author AI Partner Team
 * @since 2024-01-20
 */
@Service
@Slf4j
public class ChatHistoryServiceImpl extends ServiceImpl<ChatHistoryMapper, ChatHistory> implements ChatHistoryService {
    
    @Override
    public ChatHistory saveChatHistory(Long userId, String userMessage, String aiReply, 
                                     String modelType, Integer tokenUsage) {
        ChatHistory chatHistory = new ChatHistory();
        chatHistory.setUserId(userId);
        chatHistory.setUserMessage(userMessage);
        chatHistory.setAiResponse(aiReply);
        chatHistory.setModelName(modelType);
        chatHistory.setTokensUsed(tokenUsage);
        
        save(chatHistory);
        return chatHistory;
    }
    
    @Override
    public PageResult<ChatHistory> getConversationHistory(String conversationId, Long current, Long size) {
        Page<ChatHistory> pageObj = new Page<>(current, size);
        QueryWrapper<ChatHistory> wrapper = new QueryWrapper<>();
        wrapper.eq("conversation_id", conversationId);
        wrapper.orderByAsc("create_time");
        
        IPage<ChatHistory> result = page(pageObj, wrapper);
        
        return new PageResult<>(200, "Success", result.getRecords(), 
                               result.getTotal(), result.getPages(), 
                               result.getCurrent() > 1, result.getCurrent() < result.getPages(),
                               current.intValue(), size.intValue());
    }
    
    @Override
    public PageResult<ChatHistory> getUserChatHistory(Long userId, Integer page, Integer size, String sessionId, String modelName) {
        Page<ChatHistory> pageObj = new Page<>(page, size);
        QueryWrapper<ChatHistory> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        
        if (StringUtils.hasText(sessionId)) {
            wrapper.eq("session_id", sessionId);
        }
        if (StringUtils.hasText(modelName)) {
            wrapper.eq("model_name", modelName);
        }
        
        wrapper.orderByDesc("create_time");
        
        IPage<ChatHistory> result = page(pageObj, wrapper);
        
        return new PageResult<>(200, "Success", result.getRecords(), 
                               result.getTotal(), result.getPages(), 
                               result.getCurrent() > 1, result.getCurrent() < result.getPages(),
                               page, size);
    }
    
    @Override
    public PageResult<ChatHistory> getSessionHistory(String sessionId, Long userId, Integer page, Integer size) {
        Page<ChatHistory> pageObj = new Page<>(page, size);
        QueryWrapper<ChatHistory> wrapper = new QueryWrapper<>();
        wrapper.eq("session_id", sessionId);
        wrapper.eq("user_id", userId);
        wrapper.orderByAsc("create_time");
        
        IPage<ChatHistory> result = page(pageObj, wrapper);
        
        return new PageResult<>(200, "Success", result.getRecords(), 
                               result.getTotal(), result.getPages(), 
                               result.getCurrent() > 1, result.getCurrent() < result.getPages(),
                               page, size);
    }
    
    @Override
    public boolean deleteChatHistory(Long id, Long userId) {
        try {
            QueryWrapper<ChatHistory> wrapper = new QueryWrapper<>();
            wrapper.eq("id", id);
            wrapper.eq("user_id", userId);
            
            int deleted = baseMapper.delete(wrapper);
            return deleted > 0;
        } catch (Exception e) {
            log.error("Failed to delete chat history: {}", e.getMessage(), e);
            return false;
        }
    }
    
    @Override
    public boolean clearUserChatHistory(Long userId) {
        try {
            QueryWrapper<ChatHistory> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id", userId);
            
            int deleted = baseMapper.delete(wrapper);
            log.info("Cleared {} chat history records for user: {}", deleted, userId);
            return true;
        } catch (Exception e) {
            log.error("Failed to clear chat history for user {}: {}", userId, e.getMessage(), e);
            return false;
        }
    }
}